package main

import (
	"bufio"
	"bytes"
	"fmt"
	"strings"
)

func main() {
	comment := "Go is an open source programming language that makes it easy to build simple, " +
		"reliable,  " +
		"and efficient software."
	fmt.Println("全部的字节数:", len(comment))  // 112
	basicWriter1 := &strings.Builder{}
	size := 64
	writer1 := bufio.NewWriterSize(basicWriter1, size)
	fmt.Println("缓冲区大小:", size)
	fmt.Println()

	// WriteString方法调用Flush后，腾出空间
	start, end := 0, 41
	fmt.Println("写入字节数:", end-start)
	writer1.WriteString(comment[start:end])
	fmt.Println("缓冲区使用字节数:", writer1.Buffered())
	fmt.Println("缓冲区可用字节数:", writer1.Available())
	fmt.Println("Flush方法刷新缓冲区...")
	writer1.Flush()
	fmt.Println("缓冲区使用字节数:", writer1.Buffered())
	fmt.Println("缓冲区可用字节数:", writer1.Available())
	fmt.Println()

	// 写入的字节太多，
	start, end = 0, len(comment)  // 全部读完，所有的字节数大于缓冲区的大小
	fmt.Println("写入字节数:", end-start)
	writer1.WriteString(comment[start:end])
	fmt.Println("缓冲区使用字节数:", writer1.Buffered())
	fmt.Println("缓冲区可用字节数:", writer1.Available())
	fmt.Println("Flush方法刷新缓冲区...")
	writer1.Flush()
	fmt.Println()

	// ReadFrom会走捷径，不使用缓冲区
	basicWriter2 := &bytes.Buffer{}
	writer1.Reset(basicWriter2)
	reader := strings.NewReader(comment)
	writer1.ReadFrom(reader)
	fmt.Println("缓冲区使用字节数:", writer1.Buffered())
	fmt.Println("缓冲区可用字节数:", writer1.Available())
}
